package cn.kicsy.www.anonymous_bbs.controller;

import cn.kicsy.www.anonymous_bbs.entity.Post;
import cn.kicsy.www.anonymous_bbs.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.ArraySchema;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

@Tag(name = "帖子管理", description = "帖子相关的API接口")
@RestController
@RequestMapping("/api/posts")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    /**
     * 发布新帖子
     * @param request 帖子请求对象
     * @param httpRequest HTTP请求，用于获取用户IP地址
     * @return 创建的帖子
     */
    @Operation(summary = "发布新帖子", description = "用户发布匿名帖子")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "发布成功", content = @Content(schema = @Schema(implementation = Post.class))),
        @ApiResponse(responseCode = "400", description = "发布失败", content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
    })
    @PostMapping
    public ResponseEntity<?> createPost(@RequestBody @Parameter(description = "帖子内容请求") PostRequest request, HttpServletRequest httpRequest) {
        try {
            String ipAddress = getClientIpAddress(httpRequest);
            Post post = postService.createPost(request.getContent(), ipAddress);
            return ResponseEntity.ok(post);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取帖子列表
     * @return 帖子列表，按创建时间降序排列
     */
    @Operation(summary = "获取帖子列表", description = "获取所有帖子列表，按创建时间降序排列")
    @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(array = @ArraySchema(schema = @Schema(implementation = Post.class))))
    @GetMapping
    public List<Post> getPostList() {
        return postService.getPostList();
    }
    
    /**
     * 获取帖子详情
     * @param postId 帖子ID
     * @return 帖子详情
     */
    @Operation(summary = "获取帖子详情", description = "根据帖子ID获取帖子详细信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = Post.class))),
        @ApiResponse(responseCode = "404", description = "帖子不存在")
    })
    @GetMapping("/{postId}")
    public ResponseEntity<?> getPostById(@PathVariable @Parameter(description = "帖子ID") Long postId) {
        Post post = postService.getPostById(postId);
        if (post == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(post);
    }
    
    /**
     * 点赞帖子
     * @param postId 帖子ID
     * @param request HTTP请求，用于获取用户IP地址
     * @return 点赞后的点赞数
     */
    @Operation(summary = "点赞帖子", description = "为帖子点赞")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "点赞成功", content = @Content(schema = @Schema(implementation = LikeResponse.class))),
        @ApiResponse(responseCode = "400", description = "点赞失败", content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
    })
    @PostMapping("/{postId}/like")
    public ResponseEntity<?> likePost(@PathVariable @Parameter(description = "帖子ID") Long postId, HttpServletRequest request) {
        try {
            String ipAddress = getClientIpAddress(request);
            int likeCount = postService.likePost(postId, ipAddress);
            return ResponseEntity.ok(new LikeResponse(likeCount));
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(new ErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取客户端IP地址
     * @param request HTTP请求
     * @return 客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        
        // 如果是多个IP地址，取第一个（通常是真实IP）
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        
        return ip;
    }
    
    // 请求和响应模型类
    @Schema(description = "发布帖子请求")
    public static class PostRequest {
        private String content;
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
    }
    
    @Schema(description = "点赞响应")
    public static class LikeResponse {
        private int likeCount;
        
        public LikeResponse(int likeCount) {
            this.likeCount = likeCount;
        }
        
        public int getLikeCount() {
            return likeCount;
        }
        
        public void setLikeCount(int likeCount) {
            this.likeCount = likeCount;
        }
    }
    
    @Schema(description = "错误响应")
    public static class ErrorResponse {
        private String message;
        
        public ErrorResponse(String message) {
            this.message = message;
        }
        
        public String getMessage() {
            return message;
        }
        
        public void setMessage(String message) {
            this.message = message;
        }
    }
}